package arcane.object.game.map;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.zip.DataFormatException;

import javax.swing.Timer;

import org.jibx.runtime.JiBXException;

import arcane.jibx.io.JibxIO;

public class MapManager extends ArrayList<LinkedMap> implements ActionListener {
	protected Timer freqTimer;
	Comparator<LinkedMap> comp;
	JibxIO jibxIO;

	public MapManager() {
		super();
		jibxIO = new JibxIO(LinkedMap.class);
		freqTimer = new Timer(30000, this);
		freqTimer.setActionCommand("REMOVEMAP");
		comp = new Comparator<LinkedMap>() {
			public int compare(LinkedMap l1, LinkedMap l2) {
				if (l1.age < l2.age)
					return 1;
				else if (l1.age > l2.age)
					return -1;
				else
					return 0;
			}
		};
		freqTimer.start();
	}

	public LinkedMap loadMap(String path) throws IOException, JiBXException,
			DataFormatException {
		return (LinkedMap) jibxIO.load(path, LinkedMap.class);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("REMOVEMAP")) {
			removeOldest();
		}
	}

	/**
	 * Orders this list in ascending order based on age, and removes the last
	 * element in the list. Returns null should list size equal 0.
	 * 
	 * @return oldest linkedmap
	 */
	public LinkedMap removeOldest() {
		Collections.sort(this, comp);
		if (size() > 0)
			return remove(size() - 1);
		else
			return null;
	}

	public LinkedMap get(String mapName) {
		for (int i = 0; i < size(); i++) {
			if (get(i).getName().equals(mapName)) {
				return get(i);
			}
		}
		return null;
	}
}